//
//  AppNetRequest.m
//  MoreFun
//
//  Created by Pro on 2018/5/12.
//  Copyright © 2018年 Pro. All rights reserved.
//

#import "AppNetRequest.h"

@interface AppNetRequest ()<NSURLConnectionDelegate,NSURLConnectionDataDelegate>
{
    NSURLSessionTask * dataTask;
}
@end

@implementation AppNetRequest
+(AppNetRequest *)ShareAppNetRequestWithShowLog:(BOOL)show{
    
    AppNetRequest *itans = [[AppNetRequest alloc] initShowLog:show];
    
    return itans;
}

-(instancetype)initShowLog:(BOOL)show{
    if (self = [super init]) {
        self.showLog = show;
    }
    
    return self;
}

-(void)AF_GetNetWorkWithHeaderUrlStr:(NSString *)urlStr Parameter:(id)parameter completion:(void (^)(NSDictionary *dic,NSError *error))completion{
    
    
    if (self.showLog) {
        
        NSLog(@"上传服务器的参数:%@",[NSString stringWithFormat:@"%@%@",urlStr,parameter]);
    }
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    // 设置超时时间
    manager.requestSerializer.timeoutInterval = 30.f;
    
    // 设置对接数据类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/javascript", nil];
    
    [manager GET:urlStr parameters:parameter progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary * dict = (NSDictionary *)responseObject;
            if (self.showLog)
            {
                NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
                NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"服务器返回的结果:%@",str);
            }
            completion(dict,nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"服务器错误结果:%@",error);
        completion(nil,error);
        
    }];
    
}

-(void)AF_PostNetWorkWithHeaderUrlStr:(NSString *)urlStr Parameter:(id)parameter completion:(void (^)(NSDictionary *dic,NSError *error))completion{
    
    if (self.showLog) {
        
        NSLog(@"上传服务器的参数:%@",[NSString stringWithFormat:@"%@?%@",urlStr,parameter]);
    }
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    // 设置超时时间
    manager.requestSerializer.timeoutInterval = 30.f;
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/javascript",@"text/plain",nil];
    
    [manager POST:urlStr parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary * dict = (NSDictionary *)responseObject;
            
            if (self.showLog)
            {
                NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
                NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"服务器返回的结果:%@",str);
            }
            if ([dict[@"succeed"] intValue] == 0) {
                if ([dict[@"error_desc"] isEqualToString:@"授权过期"]) {
//                    [AppUtils exitLogin];
                }else{
                    //[MBProgressHUD showSuccess:dict[@"error_desc" ]];
                }
                
            }
            
            completion(dict,nil);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        NSLog(@"错误结果:%@",error);
        completion(nil,error);
        
        
    }];
}

#pragma mark - -图片上传 -

-(void)AF_File_postOneFileToNetWorkWithURL:(NSURL *)url body:(NSDictionary *)dic imageFileName:(NSString *)filename completion:(void (^)(NSData *data,NSError *error))completion
{
    
    if (self.showLog) NSLog(@"上传到服务器的参数:%@",dic);
    //字典里面装的是你要上传的内容
    
    NSDictionary *parameters = dic;
    //上传的接口
    //    NSString* urlstring = @"http://superqq.com/";
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url
                                                            cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                        timeoutInterval:30];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //    //要上传的图片
    UIImage *image=[dic objectForKey:filename];
    //得到图片的data
    NSData *data = UIImagePNGRepresentation(image);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    NSArray *keys= [parameters allKeys];
    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //如果key不是pic，说明value是字符类型，比如name：Boris
        if(![key isEqualToString:filename])
        {
            //添加分界线，换行
            [body appendFormat:@"%@\r\n",MPboundary];
            //添加字段名称，换2行
            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
            //添加字段的值
            [body appendFormat:@"%@\r\n",[parameters objectForKey:key]];
        }
    }
    //添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    
    [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"boris.png\"\r\n",filename];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%d", (int)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    //建立连接，设置代理
    
    
    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
    dataTask =  [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        if (self.showLog) NSLog(@"服务器返回的结果:%@",result);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                NSLog(@"错误结果:%@",error);
                completion(nil,error);
            }
            else
            {
                
                completion(data,error);
            }
            
        });
    }];
    
    [dataTask resume];
    
    
}

-(void)AF_File_postSomeFileToNetWorkWithURL:(NSString *)strUrl dicPostParams:(NSMutableDictionary *)params dicImages:(NSMutableDictionary *)dicImages completion:(void (^)(NSData *, NSError *))completion
{
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    NSURL *url = [NSURL URLWithString:strUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传的图片
    UIImage *image;//=[params objectForKey:@"pic"];
    //得到图片的data
    //NSData* data = UIImagePNGRepresentation(image);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    NSArray *keys= [params allKeys];
    
    //遍历keys
    for(int i=0;i<[keys count];i++) {
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //添加分界线，换行
        [body appendFormat:@"%@\r\n",MPboundary];
        //添加字段名称，换2行
        [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
        //[body appendString:@"Content-Transfer-Encoding: 8bit"];
        //添加字段的值
        [body appendFormat:@"%@\r\n",[params objectForKey:key]];
        //}
    }
    
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    
    //循环加入上传图片
    keys = [dicImages allKeys];
    for(int i = 0; i< [keys count] ; i++){
        //要上传的图片
        image = [dicImages objectForKey:[keys objectAtIndex:i ]];
        //得到图片的data
        NSData* data =  UIImageJPEGRepresentation(image, 0.0);
        NSMutableString *imgbody = [[NSMutableString alloc] init];
        //此处循环添加图片文件
        //添加图片信息字段
        //添加分界线，换行
        [imgbody appendFormat:@"%@\r\n",MPboundary];
        [imgbody appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@.jpg\"\r\n", [keys objectAtIndex:i], [keys objectAtIndex:i]];
        //声明上传文件的格式
        [imgbody appendFormat:@"Content-Type: application/octet-stream; charset=utf-8\r\n\r\n"];
        
        //将body字符串转化为UTF8格式的二进制
        [myRequestData appendData:[imgbody dataUsingEncoding:NSUTF8StringEncoding]];
        //将image的data加入
        [myRequestData appendData:data];
        [myRequestData appendData:[ @"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    }
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"%@\r\n",endMPboundary];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
    dataTask =  [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        if (self.showLog) NSLog(@"服务器返回的结果:%@",result);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error) {
                NSLog(@"错误结果:%@",error);
                completion(nil,error);
            }
            else
            {
                
                completion(data,error);
            }
            
        });
    }];
    
    [dataTask resume];
    
}


-(void)AF_Icon_postOneFileToNetWorkWithUrlStr:(NSString *)urlStr Parameter:(id)parameter andImageData:(NSData *)imaData Success:(void (^)(NSDictionary *dic))success  Failure:(void (^)(void))failure
{
    
    if (self.showLog) {
        
        NSLog(@"上传服务器的参数:%@",[NSString stringWithFormat:@"%@%@",urlStr,parameter]);
    }
    
    AFHTTPSessionManager *afn = [AFHTTPSessionManager manager];
    
    [afn POST:urlStr parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:imaData name:@"portrait" fileName:@"picture.jpg" mimeType:@"image/png"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary * dict = (NSDictionary *)responseObject;
            if (self.showLog)
            {
                NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
                NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"服务器返回的结果:%@",str);
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure();
        NSLog(@"服务器错误结果:%@",error);
    }];
}

#pragma mark - - 数据转换

-(NSDictionary *)dataWihtDictionary:(NSData *)data
{
    
    if (!data) {
        return nil;
    }
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
    return dic;
    
}

-(NSString *)dataWihtString:(NSData *)data
{
    
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return str;
}

@end
